package com.example.swimmingpool;

import cn.hutool.core.util.ObjectUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

public class SwimmingPoolThreadLocal {

    public SwimmingPoolThreadLocal() {
    }

    private static final String userId = "user_id";

    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    static {
        var map = threadLocal.get();
        if (ObjectUtil.isNull(map)) {
            synchronized (threadLocal) {
                map = new ConcurrentSkipListMap<>();
                threadLocal.set(map);
            }
        }

    }
    public static void put(String key, Object value) {
        var map = threadLocal.get();
        if (ObjectUtil.isNull(map)) {
            synchronized (threadLocal) {
                map = new ConcurrentSkipListMap<>();
                threadLocal.set(map);
            }
        }
        map.put(key, value);

    }

    public static Object get(String key) {
        return threadLocal.get().getOrDefault(key, "lk");
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static Long getUserId() {
        return (Long) threadLocal.get().getOrDefault(userId, 0L);
    }

    public static void putUserId(Long value) {
        put(userId, value);
    }
}
